﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Hosting;

namespace WebSite.Class
{
    public class HostHelper
    {
        protected static string DbPath = HostingEnvironment.MapPath("~/") + "App_Start/ip2region.xdb";

        public static Searcher CreateSearcher(string cachePolicy = "content")
        {
            if ("file" == cachePolicy)
            {
                return Searcher.NewWithFileOnly(DbPath);
            }

            if ("vectorIndex" == cachePolicy)
            {
                var vIndex = Searcher.LoadVectorIndexFromFile(DbPath);
                return Searcher.NewWithVectorIndex(DbPath, vIndex);
            }

            if ("content" == cachePolicy)
            {
                var cBuff = Searcher.LoadContentFromFile(DbPath);
                return Searcher.NewWithBuffer(cBuff);
            }

            throw new Exception("invalid cache policy `" + cachePolicy + "`, options: file/vectorIndex/content");
        }

        public static string GetHostInfo(string ip = "1.2.3.4")
        {
            try
            {
                var searcher = CreateSearcher();
                var region = searcher.Search(ip);
                Console.WriteLine("{{region: {0}, ioCount: {1}}}", region, searcher.IOCount);
                return region;
            }
            catch (Exception ex)
            {
                Console.WriteLine("failed to search({0}): {1}", ip, ex);
                return ex.Message;
            }
        }
    }
}